package com.nxu.service.impl;

import com.nxu.service.EmailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Service
public class EmailServiceImpl implements EmailService {
    
    private static final Logger logger = LoggerFactory.getLogger(EmailServiceImpl.class);

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String fromEmail;

    @Override
    public boolean sendVerificationCode(String to, String code) {
        try {
            logger.info("开始发送验证码邮件到: {}", to);
            
            // 验证邮箱格式
            if (!to.matches("^[A-Za-z0-9+_.-]+@(.+)$")) {
                logger.error("邮箱格式不正确: {}", to);
                return false;
            }
            
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(fromEmail);
            message.setTo(to);
            message.setSubject("药品管理系统 - 邮箱验证码");
            message.setText(String.format(
                "尊敬的用户：\n\n" +
                "您正在注册药品管理系统，验证码为：%s\n\n" +
                "验证码有效期为5分钟，请勿泄露给他人。\n" +
                "如果这不是您的操作，请忽略此邮件。\n\n" +
                "此致\n药品管理系统", 
                code
            ));
            
            logger.info("邮件内容准备完成，开始发送...");
            logger.debug("发件人: {}", fromEmail);
            logger.debug("收件人: {}", to);
            logger.debug("验证码: {}", code);
            
            mailSender.send(message);
            logger.info("验证码邮件发送成功");
            return true;
        } catch (MailException e) {
            logger.error("邮件发送失败: {}", e.getMessage(), e);
            logger.error("错误详情: {}", e.getCause() != null ? e.getCause().getMessage() : "未知错误");
            return false;
        } catch (Exception e) {
            logger.error("发送验证码时发生未知错误: {}", e.getMessage(), e);
            logger.error("错误详情: {}", e.getCause() != null ? e.getCause().getMessage() : "未知错误");
            return false;
        }
    }
} 